package com.itheima.service;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.pojo.User;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /**
     * 查询所有
     * @return
     */
    public List<Brand> selectAll(){
        //调用BrandMapper.selectAll()

        //2. 获取SQLSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4. 调用方法
        List<Brand> brands = mapper.selectAll();

        sqlSession.close();

        return brands;
    }
    /**
     * 添加
     * @param brand
     */
    public void add(Brand brand){
        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4. 调用方法
        mapper.add(brand);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }

    /**
     * 修改
     * @param id
     * @return
     */
    public Brand selectId(int id){
        //2. 获取SQLSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4. 调用方法
        Brand brand = mapper.selectId(id);

        sqlSession.close();

        return brand;
    }

    /**
     * 修改数据
     * @param brand
     */
    public void updateInformation(Brand brand) {
        //2. 获取SQLSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4. 调用方法
        mapper.updateInformation(brand);

        //提交事务
        sqlSession.commit();

        sqlSession.close();

    }

    /**
     * 删除数据
     * @param id
     */
    public void delete(int id){
        //2. 获取SQLSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4. 调用方法
        mapper.delete(id);

        //提交事务
        sqlSession.commit();

        sqlSession.close();
    }

//    /**
//     * 添加用户名
//     * @param user
//     */
//    public void addUser(User user){
//        //2. 获取SqlSession
//        SqlSession sqlSession = factory.openSession();
//        //3. 获取BrandMapper
//        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//        //4. 调用方法
//        mapper.addUser(user);
//        //提交事务
//        sqlSession.commit();
//        //释放资源
//        sqlSession.close();
//    }
}
